/**
 * \file
 *
 * \brief Empty user application template
 *
 */

/**
 * \mainpage User Application template doxygen documentation
 *
 * \par Empty user application template
 *
 * Bare minimum empty user application template
 *
 * \par Content
 *
 * -# Include the ASF header files (through asf.h)
 * -# "Insert system clock initialization code here" comment
 * -# Minimal main function that starts with a call to board_init()
 * -# "Insert application code here" comment
 *
 */

/*
 * Include header files for all drivers that have been imported from
 * Atmel Software Framework (ASF).
 */
#include <asf.h>
#include <avr32/io.h>
#include "glob.h"
#include "intc.h"
#include "compiler.h"
#include "Serial.h"
#include "Power.h"
#include "adc.h"
#include "spiLed.h"

#if GLOB_H_VERSION != 1
  #error Versionen passen nicht zusammen
#endif


extern uint16_t ledBuffer[224];

__attribute__((__interrupt__)) void Systick1ms(void){
	// Reset IRQ
	AVR32_TC.channel[0].sr;
	AdcStartConversion();
	
	
	/* TestMuster */
	static uint16_t pres = 0;
	static uint8_t pos = 180;
	pres ++;
	if (pres > 10){
		pres = 0;
		
		uint8_t i;
		for (i = 0; i < 192; i++){
			ledBuffer[ (i/12) * 14 + (i % 12) + 3] = 0;
		}

		ledBuffer[ (pos/12) * 14 + (pos % 12) + 3] = 0x8AA1;
		
		pos ++;
		if (pos >= 192) pos = 0;
		
		ledBuffer[0] = pos;
		//ledBuffer[1] = pos ++;
		AVR32_PDCA.channel[DMA_SPI_LED].tcr = 225 ;
		AVR32_PDCA.channel[DMA_SPI_LED].mar = (uint32_t)ledBuffer;
		AVR32_PDCA.channel[DMA_SPI_LED].CR.eclr = 1; // Clear error
		AVR32_PDCA.channel[DMA_SPI_LED].CR.ten = 1;  // Start transfer
	}
	
} // Systick IRQ


int main (void)
{
	// Init DebugLeds
	AVR32_GPIO.port[DebugLedPort].gpers = PIN_LED1 | PIN_LED2 | PIN_LED3 | PIN_LED4;
	AVR32_GPIO.port[DebugLedPort].oders = PIN_LED1 | PIN_LED2 | PIN_LED3 | PIN_LED4;
	AVR32_GPIO.port[DebugLedPort].ovrc  = PIN_LED1 | PIN_LED2 | PIN_LED3 | PIN_LED4;


	INTC_init_interrupts();
	Power66Mhz();
	SerialInit();
	AdcInit();
	
	Enable_global_interrupt();
	
	_printf(" \f  PoiLed V0.1\n~~~~~~~~~~~~~~~~~\n");
	Led1An();


	// Timer initialisieren (Systick)
	AVR32_TC.channel[0].CCR.clken = 1;
	AVR32_TC.channel[0].CMR.capture.wave = 0;
	AVR32_TC.channel[0].CMR.capture.tcclks = AVR32_TC_CMR0_TCCLKS_TIMER_CLOCK4;
	AVR32_TC.channel[0].CMR.capture.cpctrg = 1;
	AVR32_TC.channel[0].RC.rc = 2000;
	AVR32_TC.channel[0].CCR.swtrg = 1;
	AVR32_TC.channel[0].IER.cpcs = 1;
	INTC_register_interrupt(Systick1ms, AVR32_TC_IRQ0, 3);
	
	LedSPIInit();
	
	uint32_t altG = 0;

	while (1){
		if (altG != adcG){
			altG = adcG;
			_printf("G = %4i,  Inputvoltage = %5imV\n", altG, adcBat);
		} // if alt G
		

		
	} // while 1
} // int main
